package com.jstyle.jclife.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayoutManager;
import com.jstyle.jclife.R;
import com.jstyle.jclife.activity.HealthHistoryActivity;
import com.jstyle.jclife.activity.HeartHistoryActivity;
import com.jstyle.jclife.activity.HeartTipsActivity;
import com.jstyle.jclife.activity.HistoryActivity;
import com.jstyle.jclife.adapter.HistoryShowAdapter;
import com.jstyle.jclife.daoManager.HealthDataDaoManager;
import com.jstyle.jclife.daoManager.HeartDataDaoManager;
import com.jstyle.jclife.model.HealthData;
import com.jstyle.jclife.model.HeartData;
import com.jstyle.jclife.utils.BloodMaxComparator;
import com.jstyle.jclife.utils.BloodMinComparator;
import com.jstyle.jclife.utils.ChartDataUtil;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.ScreenUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HealthFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HealthFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.tv_health_heart)
    TextView tvHealthHeart;
//    @BindView(R.id.tv_health_hr)
//    TextView tvHomepageDate;
    @BindView(R.id.LineChartView_health_heart)
    LineChartView LineChartViewHealthHeart;
    @BindView(R.id.tv_health_blood)
    TextView tvHealthBlood;
    @BindView(R.id.tv_blood_pressure)
    TextView tvBloodPressure;
    @BindView(R.id.tv_blood_data)
    TextView tvBloodData;
    @BindView(R.id.tv_last_blood)
    TextView tvLastBlood;
    @BindView(R.id.view_blood_pressure)
    View viewBloodPressure;
    @BindView(R.id.tv_blood_avg)
    TextView tvBloodAvg;
    @BindView(R.id.tv_blood_max)
    TextView tvBloodMax;
    @BindView(R.id.tv_blood_avgValue)
    TextView tvBloodMinValue;
    @BindView(R.id.tv_blood_maxValue)
    TextView tvBloodMaxValue;
    @BindView(R.id.tv_health_hrv)
    TextView tvHealthHrv;
    @BindView(R.id.tv_hrv)
    TextView tvHrv;
    @BindView(R.id.tv_hrv_max)
    TextView tvHrvMax;
    @BindView(R.id.tv_hrv_maxValueLevel)
    TextView tvHrvMaxValueLevel;
    @BindView(R.id.tv_hrv_maxValue)
    TextView tvHrvMaxValue;
    @BindView(R.id.tv_hrv_min)
    TextView tvHrvMin;
    @BindView(R.id.tv_hrv_minValueLevel)
    TextView tvHrvMinValueLevel;
    @BindView(R.id.tv_hrv_minValue)
    TextView tvHrvMinValue;
    @BindView(R.id.tv_health_pressure)
    TextView tvHealthPressure;
    @BindView(R.id.tv_body_pressure)
    TextView tvBodyPressure;
    @BindView(R.id.tv_pressure_max)
    TextView tvPressureMax;
    @BindView(R.id.tv_pressure_maxValueLevel)
    TextView tvPressureMaxValueLevel;
    @BindView(R.id.tv_pressure_maxValue)
    TextView tvPressureMaxValue;
    @BindView(R.id.tv_pressure_min)
    TextView tvPressureMin;
    @BindView(R.id.tv_pressure_minValueLevel)
    TextView tvPressureMinValueLevel;
    @BindView(R.id.tv_pressure_minValue)
    TextView tvPressureMinValue;
    Unbinder unbinder;
    @BindView(R.id.recyclerView_health_heart)
    RecyclerView recyclerViewHealthHeart;
    @BindView(R.id.iv_hrv)
    ImageView ivHrv;
    @BindView(R.id.tv_hrv_level)
    TextView tvHrvLevel;
    @BindView(R.id.tv_hrv_value)
    TextView tvHrvValue;
    @BindView(R.id.iv_pressure)
    ImageView ivPressure;
    @BindView(R.id.tv_pressure_level)
    TextView tvPressureLevel;
    @BindView(R.id.tv_pressure_value)
    TextView tvPressureValue;

    @BindArray(R.array.string_hrv_array)
    String[] hrvContent;
    @BindArray(R.array.string_pressure_array)
    String[] stressContent;
    @BindArray(R.array.string_bp_array)
    String[] bpContent;
    @BindView(R.id.bt_health_titleLeft)
    Button btHealthTitleLeft;
    @BindView(R.id.bt_health_title)
    Button btHealthTitle;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private List<String> listContent;
    private HistoryShowAdapter historyShowAdapter;
    private Typeface mFace;

    public HealthFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HealthFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HealthFragment newInstance(String param1, String param2) {
        HealthFragment fragment = new HealthFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_health, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        mFace = Typeface.createFromAsset(getActivity().getAssets(),"Brandon_reg.otf");

        ScreenUtils.setTitleTypeface(btHealthTitle);
         ScreenUtils.setTitleTypeface(btHealthTitleLeft);
        String nowDate = DateUtil.getDefaultFormatTime(new Date());
        List<HeartData> heartDataList = HeartDataDaoManager.queryDayData(nowDate);
        initHeartView(heartDataList, nowDate);
        initHealthData(nowDate);
    }


    private void initHealthData(String date) {
        List<HealthData> healthDataList = HealthDataDaoManager.queryDayData(date);
        HealthData healthData = HealthDataDaoManager.getLastHealthData();
        if (healthData != null) {
            int hrv = healthData.getHrv();
            int pressure = healthData.getPressure();
            int highPressure = healthData.getHighBloodPressure();
            int lowPressure = healthData.getLowBloodPressure();
            tvBloodData.setText(String.valueOf(highPressure) + "/" + String.valueOf(lowPressure) + "\nmmHg");
            tvHrvValue.setText(String.valueOf(hrv));
            tvPressureValue.setText(String.valueOf(pressure));
            setHrvLevel(hrv, tvHrvValue, tvHrvLevel);
            setPressureLevel(pressure, tvPressureValue, tvPressureLevel);
        }
        if(healthDataList==null||healthDataList.size()==0)return;
        int maxHrv = 0;
        int maxPressure = 0;
        int minHrv = 300;
        int minPressure = 300;
        int maxBloodHigh = 0;
        int maxBloodLow = 0;


        for (HealthData healthData1 : healthDataList) {
            int hrv = healthData1.getHrv();
            int pressure = healthData1.getPressure();
            maxHrv = Math.max(maxHrv, hrv);
            minHrv = Math.min(minHrv, hrv);
            maxPressure = Math.max(maxPressure, pressure);
            minPressure = Math.min(minPressure, pressure);
        }
        Collections.sort(healthDataList,new BloodMaxComparator());
        HealthData maxBlood=healthDataList.get(healthDataList.size()-1);
        maxBloodHigh=maxBlood.getHighBloodPressure();
        maxBloodLow=maxBlood.getLowBloodPressure();
        Collections.sort(healthDataList,new BloodMinComparator());
        HealthData maxMin=healthDataList.get(0);
        int avgHigh=maxMin.getHighBloodPressure();
        int avgLow=maxMin.getLowBloodPressure();

        minHrv = minHrv == 300 ? 0 : minHrv;
        minPressure = minPressure == 300 ? 0 : minPressure;

        setPressureLevel(maxPressure, tvPressureMaxValue, tvPressureMaxValueLevel);
        setPressureLevel(minPressure, tvPressureMinValue, tvPressureMinValueLevel);
        setHrvLevel(maxHrv, tvHrvMaxValue, tvHrvMaxValueLevel);
        setHrvLevel(minHrv, tvHrvMinValue, tvHrvMinValueLevel);


        tvBloodMaxValue.setText(String.valueOf(maxBloodHigh) + "/" + String.valueOf(maxBloodLow) + " mmHg");
        tvBloodMinValue.setText(String.valueOf(avgHigh) + "/" + String.valueOf(avgLow) + " mmHg");
    }



    private void setHrvLevel(int hrv, TextView textViewValue, TextView textViewLevel) {
        String levelHrv = "--";
        int color = Color.WHITE;
        if (hrv > 0 && hrv < 26) {
            levelHrv = hrvContent[3];
            color = getResources().getColor(R.color.hrv_level_0);
        } else if (hrv >= 26 && hrv < 37) {
            levelHrv = hrvContent[2];
            color = getResources().getColor(R.color.hrv_level_1);
        } else if (hrv >= 37 && hrv < 55) {
            levelHrv = hrvContent[1];
            color = getResources().getColor(R.color.hrv_level_2);
        } else if (hrv >= 55) {
            levelHrv = hrvContent[0];
            color = getResources().getColor(R.color.hrv_level_3);
        }
        textViewValue.setTextColor(color);
        textViewValue.setText(String.valueOf(hrv == 0 ? "--" : hrv));
        textViewLevel.setText(levelHrv);
        textViewLevel.setTextColor(color);
    }

    private void setPressureLevel(int pressure, TextView textViewValue, TextView textViewLevel) {
        String levelHrv = "--";
        int color = Color.WHITE;
        if (pressure > 0 && pressure < 25) {
            levelHrv = stressContent[0];
            color = getResources().getColor(R.color.hrv_level_3);
        } else if (pressure >= 25 && pressure < 50) {
            levelHrv = stressContent[1];
            color = getResources().getColor(R.color.hrv_level_2);
        } else if (pressure >= 50 && pressure < 75) {
            levelHrv = stressContent[2];
            color = getResources().getColor(R.color.hrv_level_1);
        } else if (pressure >= 75) {
            levelHrv = stressContent[3];
            color = getResources().getColor(R.color.hrv_level_0);

        }
        textViewValue.setTextColor(color);
        textViewValue.setText(String.valueOf(pressure == 0 ? "--" : pressure));
        textViewLevel.setText(levelHrv);
        textViewLevel.setTextColor(color);
    }

    private void initHeartView(List<HeartData> heartDataList, String queryDate) {
        FlexboxLayoutManager layoutManager2 = new FlexboxLayoutManager(getActivity());
        listContent = new ArrayList<>();
        listContent.add(getString(R.string.avg_hr));
        listContent.add(getString(R.string.Minimum_HR));
        listContent.add(getString(R.string.Maximum_HR));
        historyShowAdapter = new HistoryShowAdapter(listContent);
        historyShowAdapter.showBottomView(false);
        recyclerViewHealthHeart.setAdapter(historyShowAdapter);
        recyclerViewHealthHeart.setLayoutManager(layoutManager2);
        int maxDayHr = 0;
        int minDayHr = 300;
        int totalDayHr = 0;
        int count = 0;
        int offsetCount = 5;
        int firstCount = -1;
        HashMap<Integer,Integer> offsetMap=new HashMap<>();
        for (int i = 0; i < heartDataList.size(); i++) {
            HeartData heartData = heartDataList.get(i);
            String date = heartData.getTime();
            int startCount = DateUtil.getMIndex(date, queryDate.split(" ")[0] + " 00:00:00",1);
            int heartRate = heartData.getHeart();
            // if (startCount >= 1440) break;
            if (heartRate != 0) {

                count++;
                totalDayHr += heartRate;
                maxDayHr = Math.max(maxDayHr, heartRate);
                minDayHr = Math.min(minDayHr, heartRate);
            }

        }


        int[] heartArray = new int[1440];//24*60分钟
        for (int i = 0; i < heartDataList.size(); i++) {
            HeartData heartData = heartDataList.get(i);
            String date = heartData.getTime();
            int startCount = DateUtil.getMIndex(date, queryDate.split(" ")[0] + " 00:00:00",1);
            int heartRate = heartData.getHeart();
            if (startCount >= 1440) break;
            if(heartRate!=0){
                heartArray[startCount]=heartRate;
            }
        }
        List<String> listHeart = new ArrayList<>();//总计列表
        int avgHR = count == 0 ? 0 : totalDayHr / count;
        listHeart.add(avgHR + " bpm");
        listHeart.add((minDayHr == 300 ? 0 : minDayHr) + " bpm");
        listHeart.add(maxDayHr + " bpm");
        float top=0;
        if(maxDayHr%10==0){
            top=maxDayHr;
        }else{
            top=(((int)maxDayHr/10)+1)*10;
        }
        historyShowAdapter.setDividerColor(Color.WHITE);
        historyShowAdapter.setStepData(listHeart);
        ChartDataUtil.initDataChartView(LineChartViewHealthHeart, -0.5f, top+10, heartArray.length, 40);
        LineChartViewHealthHeart.setLineChartData(ChartDataUtil.getHistoryHeartDayChart(getActivity(), heartArray,mFace,0,top));
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) init();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.tv_health_hr, R.id.tv_blood_pressure, R.id.tv_body_pressure, R.id.tv_hrv, R.id.tv_health_heart, R.id.tv_health_blood, R.id.tv_health_hrv, R.id.tv_health_pressure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_health_hr:
                startTipsActivity(HeartTipsActivity.TipsType_Heart);
                break;
            case R.id.tv_blood_pressure:
                startTipsActivity(HeartTipsActivity.TipsType_BLOOD);
                break;
            case R.id.tv_body_pressure:
                startTipsActivity(HeartTipsActivity.TipsType_Stress);
                break;
            case R.id.tv_hrv:
                startTipsActivity(HeartTipsActivity.TipsType_HRV);
                break;
            case R.id.tv_health_heart:
                startActivity(HeartHistoryActivity.class);
                break;
            case R.id.tv_health_blood:
                startHealthActivity(HealthHistoryActivity.DATA_BLOOD);
                break;
            case R.id.tv_health_hrv:
                startHealthActivity(HealthHistoryActivity.DATA_HRV);
                break;

            case R.id.tv_health_pressure:
                startHealthActivity(HealthHistoryActivity.DATA_PRESSURE);
                break;
        }
    }

    private void startHealthActivity(int type) {
        Intent intent = new Intent(getActivity(), HealthHistoryActivity.class);
        intent.putExtra(HistoryActivity.KEY_DATA_TYPE, type);
        startActivity(intent);
    }

    private void startTipsActivity(int type) {
        Intent intent = new Intent(getActivity(), HeartTipsActivity.class);
        intent.putExtra(HeartTipsActivity.TipsType, type);
        startActivity(intent);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
